#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <cstdio>
#include <functional>
#include "logger.hpp"
using namespace logger_module;
namespace thread_module
{
    class thread
    {
     using func_t = std::function<void()>;
    private:
    //加static是因为类中函数带有隐式的this指针,类型不符合线程创建的所需函数指针,加个static修饰可以解决这个问题 
    static void* routine(void* arg)
    {
        thread* self=(thread*)arg;
        self->_is_running=true;
        pthread_setname_np(self->_tid,self->_name.c_str());
        //LOG(log_level::INFO) << self->_name << " 线程开始执行 routine()";
        self->_func();
        //LOG(log_level::DEBUG)<<"线程结束了";
        return nullptr;
    }
    public:
        thread(func_t func)
        :_tid(0),
        _is_running(false),
        _is_detaching(false),
        _func(func)
        {
             _name = "thread-" + std::to_string(_number++);
        }
        std::string name()
        {
            return _name;
        }
        void start()
        {
            if(_is_running)
            {
                //printf("线程已经在运行了\n");
                return;
            }
            if(_is_detaching)
            {
                //printf("线程已经分离了\n");
                return;
            }
            int n=pthread_create(&_tid,nullptr,routine,this);
            if(n!=0)
            {
                std::cerr<<strerror(n)<<std::endl;
                return;
            }
            //printf("线程运行成功\n");

        }
        void detach()
        {
            if(!_is_running)
            {
                //printf("线程还没运行\n");
                return;
            }
            if(_is_detaching)
            {
                //printf("线程已经被分离了\n");
                return;
            }
            int n=pthread_detach(_tid);
            if(n!=0)
            {
                std::cerr<<strerror(n)<<std::endl;
                return;
            }
            _is_detaching=true;
            //printf("线程分离成功\n");
        }
        void join()
        {
            if(_is_detaching)
            {
               // printf("线程被分离了,无法等待\n");
                return;
            }
            if(!_is_running)
            {
               // printf("线程还没启动,无法等待\n");
            }
            int n=pthread_join(_tid,nullptr);
            if(n!=0)
            {
                std::cerr<<strerror(n)<<std::endl;
                return;
            }
            //printf("join成功\n");
        }
        pthread_t get_tid()
        {
            return _tid;
        }
        ~thread(){}
    private:
        static int _number;
        pthread_t _tid;
        std::string _name;
        bool _is_running;
        bool _is_detaching;
        func_t _func;
    };
    int thread::_number =0;
}